package l4;


import java.util.ArrayList;
import java.util.LinkedList;

public class product<T> implements list<T>{
    public static class Node<T>{
        T data;
        Node<T> next;

        public Node(T data) {
            this.data = data;
            this.next = null;
        }
    }
    private Node<T> head;
    private int size;
    public product(){
        head = null;
        size = 0;
    }

    @Override
    public void insert(int index, T value) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("索引越界");
        }

        Node<T> newnode =new Node<>(value);
        if (index == 0){
            newnode.next=head;
            head=newnode;
        }else {
            Node<T> current = head;
            for (int i = 0; i < index-1; i++) {
                current = current.next;
            }
            newnode.next = current.next;
            current.next = newnode;

        }
        size++;
    }

    @Override
    public void remove(int index) {

        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("索引越界");
        }

        Node<T> current = head;

        if (index == 0){
            head = head.next;
        }else {
            for (int i = 0; i < index-1; i++) {
                current = current.next;
            }
            current.next = current.next.next;
        }
        size--;
    }

    @Override
    public int search(T value) {
        Node<T> current = head;
        for (int i = 0; i < size; i++){
            if (current.data.equals(value)){
                return i;
            }
            current = current.next;
        }
        return -1;
    }

    @Override
    public T visit(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("索引越界");
        }

        Node<T> current = head;
        for (int i = 0; i < index; i++) {
            current = current.next;
        }
        return current.data;
    }

    @Override
    public void update(int index, T value) {

    }

    @Override
    public void traverse() {
        Node<T> current = head;
        while (current != null){
            System.out.println(current.data);
            current = current.next;
        }

    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public int size() {
        return size;
    }
}
